import { createRouter, createWebHistory } from "vue-router";
import { useMenu, useUserInfo, useToken } from "@/store/index.js";
import NProgress from "nprogress";
import "nprogress/nprogress.css"; // progress bar style
import layout from "@/views/layout/index";
const routes = [
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/index"),
    meta: {
      requiresAuth: false,
      title: "登录",
      transition: "default",
    },
  },
  {
    path: "/",
    component: layout,
    redirect: "/home",
    meta: {
      transition: "default",
    },
    children: [
      {
        path: "/home",
        name: "home",
        component: () => import("@/views/home/index"),
        meta: {
          requiresAuth: true,
          title: "首页",
        },
      },
    ],
  },
  {
    path: "/error/404",
    name: "404",
    component: layout,
    children: [
      {
        path: "/404",
        name: "404",
        component: () => import("@/views/error/404"),
        meta: {
          requiresAuth: false,
          title: "404",
        },
      },
    ],
  },
  {
    path: "/error/403",
    name: "403",
    component: layout,
    children: [
      {
        path: "/403",
        name: "403",
        component: () => import("@/views/error/403.vue"),
        meta: {
          requiresAuth: false,
          title: "403",
        },
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const tokenStore = useToken();
  const userInfo = useUserInfo();
  const token = tokenStore.token || "";
  // 如果目标是登录页，直接放行
  if (to.path === "/login") {
    next();
    return;
  }

  // 如果没有 token 且目标页面需要认证，则跳转到登录页
  if (!token && to.meta.requiresAuth) {
    next("/login");
  } else if (token) {
    // 有 token 的情况下检查页面权限
    // 如果是公共页面（不需要权限），直接放行
    // if (!to.meta.requiresAuth) {
    //   next();
    //   return;
    // }

    // 获取用户权限列表（这里需要根据你的实际存储方式调整）
    // 假设权限存储在 menuStore 或 routesStore 中
    const userPermissions = userInfo.userInfo.permissions || [];

    // 检查路由是否存在
    const routeExists = router
      .getRoutes()
      .some((route) => route.path === to.path);

    // 检查是否有页面访问权限
    const hasPermission = to.meta.permission
      ? userPermissions.includes(to.meta.permission)
      : true; // 如果没有设置权限要求，则默认允许访问

    if (routeExists && hasPermission) {
      next();
    } else if (!routeExists) {
      next("/404"); // 路由不存在跳转到404
    } else {
      next("/403"); // 没有权限跳转到403
    }
  } else {
    // 不需要认证的页面直接放行
    next();
  }
});

router.afterEach((to) => {
  NProgress.done();
});

export default router;
